package com.dq.redis.xiaoxi;


import com.dq.redis.xiaoxi.realize.RedisSubscriberRealize;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 配置监听 文件
 *
 * @author 凡
 */
@Configuration
@EnableCaching
public class RedisSubscriberConfig {

    /**
     * Redis消息监听器 容器
     * @Qualifier("redisConnectionFactory")
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(@Qualifier("redisConnectionFactory") RedisConnectionFactory connectionFactory) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        List<PatternTopic> list =  new ArrayList<>();
        // __keyevent@0__:expired : 失效KEY 监听, 监听事件获取的 是失效 key
        list.add(new PatternTopic("__keyevent@0__:expired"));
        list.add(new PatternTopic("goods_channel_2"));
        container.addMessageListener(listenerAdapter(new RedisSubscriberRealize()), list);

        return container;
    }


    /**
     * 配置消息接收处理类
     * @param messageListener  自定义消息接收类
     * @return
     */
    @Bean
    @Scope("prototype")// 设置多例模式
    MessageListenerAdapter listenerAdapter(MessageListener messageListener) {
        // 继承MessageListener, 重写onMessage方法
        return new MessageListenerAdapter(messageListener);
    }
}
